package com.pshcp.common.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @Description: TODO
 * @Author: xiaoche
 * @Date: 2022/12/8 14:58
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
public class WxMaConfiguration {

    private final WxMaProperties properties;

    private static WxMaService wxMaService;

    @Autowired
    public WxMaConfiguration(WxMaProperties properties) {
        this.properties = properties;
    }

    public static WxMaService getMaService() {
        if (wxMaService == null) {
            throw new IllegalArgumentException("未找到对应的配置，请核实！");
        }
        return wxMaService;
    }


    @PostConstruct
    public void init() {
        WxMaProperties configs = this.properties;
        if (configs == null) {
            throw new WxRuntimeException("配置错误");
        }
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(configs.getAppid());
        config.setSecret(configs.getSecret());
        config.setToken(configs.getToken());
        config.setAesKey(configs.getAesKey());
        config.setMsgDataFormat(configs.getMsgDataFormat());
        WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(config);
        wxMaService=service;
    }
}
